package m4;

import com.rabbitmq.client.*;

import java.util.Scanner;
import java.util.UUID;

/*
    2022/1/20
    16:42
*/public class Consumer {
    public static void main(String[] args) throws Exception{
        //连接服务器
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.64.140");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //2.声明随机队列，
        String queue = UUID.randomUUID().toString();
        channel.queueDeclare(queue,false,true,true,null);
        //2.1声明交换机
        channel.exchangeDeclare("direct_logs","direct");
        //2.2使用绑定关键词绑定
        System.out.println("请输入绑定键关键词，用空格隔开:");
        String s = new Scanner(System.in).nextLine();
        String[] split = s.split("\\s+");
        for (int i = 0; i < split.length; i++) {
            channel.queueBind(queue,"direct_logs",split[i]);
        }

        //接收消息
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println(new String(message.getBody(),"UTF-8")+"->"+message.getEnvelope().getRoutingKey());
        };
        CancelCallback cancelCallback = consumerTag -> {};
        channel.basicConsume(queue,true,deliverCallback,cancelCallback);

    }
}
